package com.soonfor.evaluate.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.bean.ReturnMsgEntity;
import com.estronger.shopmanage.utils.JsonUtil;
import com.estronger.shopmanage.utils.PrefUtils;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.DoubleUtils;
import com.soonfor.evaluate.base.EvalBaseActivity;
import com.soonfor.evaluate.bean.UploadImageBean;
import com.soonfor.evaluate.bean.UploadPhoto;
import com.soonfor.evaluate.http.api.Request;
import com.soonfor.evaluate.http.httptools.AsyncUtils;
import com.soonfor.evaluate.tools.ComToast;
import com.soonfor.evaluate.tools.CustomDialog;
import com.soonfor.evaluate.tools.UserInfo;
import com.soonfor.evaluate.tools.dialog.normal.NormalDialog;
import com.soonfor.evaluate.tools.dialog.normal.OnBtnClickL;
import com.soonfor.evaluate.view.UploadImageView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者：DC-DingYG on 2018-11-14 19:50
 * 邮箱：dingyg012655@126.com
 */
public class ReplyActivity extends EvalBaseActivity {
    private Activity mActivity;
    @BindView(R.id.etfEvalContent)
    EditText etfReplay;
    @BindView(R.id.llfUploadPics)
    UploadImageView viewUploadPics;

    private String[] evalArray;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_replay;
    }

    @Override
    protected void initPresenter() {
        toolbar.findViewById(R.id.ivfLeft).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InFinish();
            }
        });
    }

    @Override
    protected void initViews() {
        mActivity = ReplyActivity.this;
        evalArray = getIntent().getStringArrayExtra("EVALIDPRAMS");
        if (evalArray != null) {
            etfReplay.setText(evalArray[3]);
            etfReplay.setSelection(evalArray[3].length());
        }
        viewUploadPics.initUploadImgView(mActivity);
        List<String> pics = getIntent().getStringArrayListExtra("IMAGEPATHS");
        List<UploadPhoto> photos = new ArrayList<>();
        if (pics != null && pics.size() > 0) {
            for (int i = 0; i < pics.size(); i++) {
                UploadPhoto uphoto = new UploadPhoto();
                LocalMedia lm = new LocalMedia();
                lm.setCompressPath(pics.get(i));
                lm.setPath(pics.get(i));
                uphoto.setLocalMedia(lm);
                uphoto.setUrl(pics.get(i));
                photos.add(uphoto);
            }
        }
        viewUploadPics.refreshView(photos);
    }

    @Override
    protected void updateViews(boolean isRefresh) {
    }

    @OnClick({R.id.tvfSave})
    void thisClickListener() {
        if (!DoubleUtils.isFastDoubleClick()) {
            List<UploadImageBean> attachDtos = new ArrayList<>();
            if (viewUploadPics.getImgList().size() > 0) {
                List<UploadPhoto> photos = viewUploadPics.getImgList();
                boolean isUploaded = true;//是否都上传成功
                for (int i = 0; i < photos.size(); i++) {
                    String url = photos.get(i).getLocalMedia().getCompressPath();
                    if (url == null || !url.startsWith("http")) {
                        isUploaded = false;
                        break;
                    } else {
                        UploadImageBean uiBean = new UploadImageBean();
                        uiBean.setFpath(photos.get(i).getUrl());
                        attachDtos.add(uiBean);
                    }
                }
                if (!isUploaded) {
                    attachDtos.clear();
                    ComToast.showToast(mActivity, "尚有图片未上传成功，请稍候或重新上传");
                    closeLoadingDialog();
                    return;
                }
            }
            saveData(attachDtos);
        }
    }

    NormalDialog ndialog;

    private void saveData(final List<UploadImageBean> attachDtos) {
        final String Scontent = etfReplay.getText().toString().trim();
        if (Scontent.equals("") && attachDtos.size() == 0) {
            ComToast.showToast(mActivity, "请编辑内容后再提交");
            return;
        }
        ndialog = CustomDialog.getInstance().getNormalDialog(mActivity, "温馨提示", "确定要保存回复内容吗？",
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick(View view) {
                        ndialog.dismiss();
                        Map<String, String> params = new HashMap<>();
                        try {
                            params.put("sf_action", "savereply");
                            params.put("usercode", PrefUtils.getString(mActivity, "userName", ""));
                            params.put("fappraiseoriid", evalArray[0]);
                            params.put("fappraiseoritype", evalArray[1]);
                            params.put("fifrtnvisittask", evalArray[2]);
                            params.put("freply", Scontent);//回复内容
                            params.put("replyimgs", new Gson().toJson(attachDtos));
                        } catch (Exception e) {
                        }
                        showLoadingDialog();
                        Request.Evaluate.replyToThat(mActivity, 1014, UserInfo.COMMON_URL_BASE, params, new AsyncUtils.AsyncCallback() {

                            @Override
                            public void success(int requestCode, String object) {
                                ReturnMsgEntity resultEntity = JsonUtil.returnMsgEntity(object);
                                closeLoadingDialog();
                                if (resultEntity.getSuccess()) {
                                    ComToast.showFailToast(mActivity, "回复成功");
                                    Intent intent = new Intent(mActivity, Evaluate_CustomersToMeDetailActivity.class);
                                    mActivity.setResult(Activity.RESULT_OK, intent);//Result_OK 表示结果响应成功
                                    mActivity.finish();
                                } else {
                                    ComToast.showFailToast(mActivity, "回复不成功");
                                }
                            }

                            @Override
                            public void fail(int requestCode, int statusCode, String data, String msg) {
                                closeLoadingDialog();
                                ComToast.showFailToast(mActivity, "回复不成功");
                            }
                        });
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && data != null) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> medias = PictureSelector.obtainMultipleResult(data);
                    if (medias != null && medias.size() > 0) {
                        List<UploadPhoto> photos = new ArrayList<>();
                        for (int i = 0; i < medias.size(); i++) {
                            UploadPhoto photo = new UploadPhoto();
                            photo.setLocalMedia(medias.get(i));
                            photo.setLocalUrl(medias.get(i).getCompressPath());
                            photos.add(photo);
                        }
                        viewUploadPics.refreshView(photos);
                    }
                    break;
            }
        }
    }

    Dialog quitConfirmDialog = null;

    private void InFinish() {
        if (!etfReplay.getText().toString().trim().equals("") || (viewUploadPics != null && viewUploadPics.getImgList().size() == 0)) {
            quitConfirmDialog = CustomDialog.getNormalDialog(mActivity, "温馨提示", "编辑的内容未提交，确认要离开吗",
                    new OnBtnClickL() {
                        @Override
                        public void onBtnClick(View view) {
                            quitConfirmDialog.dismiss();
                            finish();
                        }
                    });
        } else {
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        InFinish();
    }
}
